"""
Case Type   : GUC
Case Name   : 使用alter database方法设置参数default_tablespace为不存在的名称，合理报错
Create At   : 2020/12/2
Owner       : zhuanghuan96
Description :
    1.查询default_tablespace默认值
    2.创建数据库
    3.修改指定数据库的default_tablespace为不存在的名称并查询
Expect      :
    1.显示默认值为空
    2.数据库创建成功
    3.发出notice，默认值仍然是空
History     :
    Modified by opentestcase046 2022/08/10:优化用例，删除影响索引取值的多余信息，保证断言成功
"""
import os
import unittest

from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class ClientConnection(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.Constant = Constant()
        self.commonsh = CommonSH('dbuser')
        self.db_name = 'test_spdb_029'

    def test_default_tablespace(self):
        text = '-----step1:查询default_tablespace默认值;expect:显示默认值为空-----'
        self.log.info(text)
        res1 = self.commonsh.execut_db_sql(f"show default_tablespace;")
        self.log.info(res1)
        self.assertTrue(len(res1.splitlines()) > 1, f'执行失败:{text}')
        self.assertTrue(res1.splitlines()[-2].strip() == '', f'执行失败:{text}')

        text = '-----step2:创建数据库;expect:数据库创建成功-----'
        self.log.info(text)
        res2 = self.commonsh.execut_db_sql(
            f"drop database if exists {self.db_name};"
            f"create database {self.db_name};")
        self.log.info(res2)
        self.assertIn(self.Constant.CREATE_DATABASE_SUCCESS,
                      res2, f'执行失败:{text}')

        text = '-----step3:修改指定数据库的default_tablespace为不存在的名称并' \
               '查询;expect:发出notice，默认值仍然是空-----'
        self.log.info(text)
        res3 = self.commonsh.execut_db_sql(
            f"alter database {self.db_name} "
            f"set default_tablespace to 't_tablespace029';")
        self.log.info(res3)
        self.assertIn('NOTICE:  tablespace "t_tablespace029" does not exist',
                      res3, f'执行失败:{text}')
        res = self.commonsh.execut_db_sql(
            "show default_tablespace;", dbname=self.db_name)
        self.log.info(res)
        rows = res.splitlines()
        for row in rows[::-1]:
            if row == '' or row.startswith('WARNING') or row.startswith('DETAIL'):
                rows.remove(row)
        self.assertTrue(len(rows) > 1, f'执行失败:{text}')
        self.assertTrue(rows[-2].strip() == '', f'执行失败:{text}')

    def tearDown(self):
        self.log.info('-----清理环境-----')
        res = self.commonsh.execut_db_sql(
            f"drop database if exists {self.db_name};")
        self.log.info(res)
        self.assertEqual(self.Constant.DROP_DATABASE_SUCCESS, res)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
